Object.defineProperty(exports, '__esModule', {
    value: true
});
exports.default = void 0;
var e = require('../../../../@babel/runtime/helpers/typeof');
var t = require('../../../../@babel/runtime/helpers/createForOfIteratorHelper');
var n = require('../../../../@babel/runtime/helpers/slicedToArray');
var i = require('../../../../@babel/runtime/helpers/classCallCheck');
var a = require('../../../../@babel/runtime/helpers/createClass');
var o = require('./util');
var r = require('./sha1');
var c = 6291456;
var s = {};
var l = (function () {
    function e() {
        i(this, e);
        if (getApp().globalData.PAINTER_MAX_LRU_SPACE) {
            c = getApp().globalData.PAINTER_MAX_LRU_SPACE;
        }
        uni.getStorage({
            key: 'savedFiles',
            success: function (e) {
                if (e.data) {
                    s = e.data;
                }
            }
        });
    }

    a(e, [
        {
            key: 'download',
            value: function (e, t) {
                return new Promise(function (i, a) {
                    if (e && o.isValidUrl(e)) {
                        var c = (function (e) {
                            if (o.isDataUrl(e)) {
                                var t = /data:image\/(\w+);base64,(.*)/.exec(e) || [];
                                var i = n(t, 3);
                                var a = i[1];
                                var c = i[2];
                                return ''.concat(r.hex_sha1(c), '.').concat(a);
                            }
                            return e;
                        })(e);
                        if (t) {
                            var l = (function (e) {
                                if (!s[e]) {
                                    return;
                                }
                                s[e].time = new Date().getTime();
                                uni.setStorage({
                                    key: 'savedFiles',
                                    data: s
                                });
                                return s[e];
                            })(c);
                            if (l) {
                                if (-1 !== l.path.indexOf('//usr/')) {
                                    uni.getFileInfo({
                                        filePath: l.path,
                                        success: function () {
                                            i(l.path);
                                        },
                                        fail: function (n) {
                                            console.error('base64 file broken, '.concat(JSON.stringify(n)));
                                            f(e, t).then(
                                                function (e) {
                                                    i(e);
                                                },
                                                function () {
                                                    a();
                                                }
                                            );
                                        }
                                    });
                                } else {
                                    uni.getFileSystemManager().getFileInfo({
                                        filePath: l.path,
                                        success: function (e) {
                                            i(l.path);
                                        },
                                        fail: function (n) {
                                            console.error('the file is broken, redownload it, '.concat(JSON.stringify(n)));
                                            u(e, t).then(
                                                function (e) {
                                                    i(e);
                                                },
                                                function () {
                                                    a();
                                                }
                                            );
                                        }
                                    });
                                }
                            } else {
                                if (o.isOnlineUrl(e)) {
                                    u(e, t).then(
                                        function (e) {
                                            i(e);
                                        },
                                        function () {
                                            a();
                                        }
                                    );
                                } else {
                                    if (o.isDataUrl(e)) {
                                        f(e, t).then(
                                            function (e) {
                                                i(e);
                                            },
                                            function () {
                                                a();
                                            }
                                        );
                                    }
                                }
                            }
                        } else {
                            uni.getFileInfo({
                                filePath: c,
                                success: function () {
                                    i(e);
                                },
                                fail: function () {
                                    if (o.isOnlineUrl(e)) {
                                        u(e, t).then(
                                            function (e) {
                                                i(e);
                                            },
                                            function () {
                                                a();
                                            }
                                        );
                                    } else {
                                        if (o.isDataUrl(e)) {
                                            f(e, t).then(
                                                function (e) {
                                                    i(e);
                                                },
                                                function () {
                                                    a();
                                                }
                                            );
                                        }
                                    }
                                }
                            });
                        }
                    } else {
                        i(e);
                    }
                });
            }
        }
    ]);
    return e;
})();

function f(e, t) {
    return new Promise(function (i, a) {
        var o = /data:image\/(\w+);base64,(.*)/.exec(e) || [];
        var c = n(o, 3);
        var s = c[1];
        var l = c[2];
        if (!s) {
            console.error('base parse failed');
            return void a();
        }
        var f = ''.concat(r.hex_sha1(l), '.').concat(s);
        var u = ''.concat(uni.env.USER_DATA_PATH, '/').concat(f);
        var h = uni.base64ToArrayBuffer(l.replace(/[\r\n]/g, ''));
        uni.getFileSystemManager().writeFile({
            filePath: u,
            data: h,
            encoding: 'binary',
            success: function () {
                uni.getFileInfo({
                    filePath: u,
                    success: function (e) {
                        var n = e.size;
                        t
                            ? v(n).then(
                                function () {
                                    d(f, n, u, true).then(function (e) {
                                        i(e);
                                    });
                                },
                                function () {
                                    i(u);
                                }
                            )
                            : i(u);
                    },
                    fail: function (e) {
                        console.error('getFileInfo '.concat(u, ' failed, ').concat(JSON.stringify(e)));
                        i(u);
                    }
                });
            },
            fail: function (e) {
                console.log(e);
            }
        });
    });
}

function u(e, t) {
    return new Promise(function (n, i) {
        uni.downloadFile({
            url: e,
            success: function (a) {
                if (200 !== a.statusCode) {
                    console.error('downloadFile '.concat(e, ' failed res.statusCode is not 200'));
                    return void i();
                }
                var o = a.tempFilePath;
                uni.getFileInfo({
                    filePath: o,
                    success: function (i) {
                        var a = i.size;
                        t
                            ? v(a).then(
                                function () {
                                    d(e, a, o).then(function (e) {
                                        n(e);
                                    });
                                },
                                function () {
                                    n(o);
                                }
                            )
                            : n(o);
                    },
                    fail: function (e) {
                        console.error('getFileInfo '.concat(a.tempFilePath, ' failed, ').concat(JSON.stringify(e)));
                        n(a.tempFilePath);
                    }
                });
            },
            fail: function (e) {
                console.error('downloadFile failed, '.concat(JSON.stringify(e), ' '));
                i();
            }
        });
    });
}

function d(e, t, n) {
    var i = arguments.length > 3 && void 0 !== arguments[3] && arguments[3];
    return new Promise(function (a, o) {
        if (i) {
            var r = s.totalSize ? s.totalSize : 0;
            s[e] = {};
            s[e].path = n;
            s[e].time = new Date().getTime();
            s[e].size = t;
            s.totalSize = t + r;
            uni.setStorage({
                key: 'savedFiles',
                data: s
            });
            return void a(n);
        }
        uni.saveFile({
            tempFilePath: n,
            success: function (n) {
                var i = s.totalSize ? s.totalSize : 0;
                s[e] = {};
                s[e].path = n.savedFilePath;
                s[e].time = new Date().getTime();
                s[e].size = t;
                s.totalSize = t + i;
                uni.setStorage({
                    key: 'savedFiles',
                    data: s
                });
                a(n.savedFilePath);
            },
            fail: function (t) {
                console.error('saveFile '.concat(e, ' failed, then we delete all files, ').concat(JSON.stringify(t)));
                a(n);
                h();
            }
        });
    });
}

function h() {
    uni.removeStorage({
        key: 'savedFiles',
        success: function () {
            uni.getSavedFileList({
                success: function (e) {
                    g(e.fileList);
                },
                fail: function (e) {
                    console.error('getSavedFileList failed, '.concat(JSON.stringify(e)));
                }
            });
        }
    });
}

function v(e) {
    return e > c
        ? Promise.reject()
        : new Promise(function (n, i) {
            var a = s.totalSize ? s.totalSize : 0;
            if (e + a <= c) {
                n();
            } else {
                var o = [];
                var r = JSON.parse(JSON.stringify(s));
                delete r.totalSize;
                var l;
                var f = Object.keys(r).sort(function (e, t) {
                    return r[e].time - r[t].time;
                });
                var u = t(f);
                try {
                    for (u.s(); !(l = u.n()).done;) {
                        var d = l.value;
                        a -= s[d].size;
                        o.push(s[d].path);
                        delete s[d];
                        if (a + e < c) {
                            break;
                        }
                    }
                } catch (e) {
                    console.log('CatchClause', e);
                    console.log('CatchClause', e);
                    u.e(e);
                } finally {
                    u.f();
                }
                s.totalSize = a;
                uni.setStorage({
                    key: 'savedFiles',
                    data: s,
                    success: function () {
                        if (o.length > 0) {
                            g(o);
                        }
                        n();
                    },
                    fail: function (e) {
                        console.error('doLru setStorage failed, '.concat(JSON.stringify(e)));
                        i();
                    }
                });
            }
        });
}

function g(n) {
    var i;
    var a = t(n);
    try {
        var o = function () {
            var t = i.value;
            var n = t;
            if ('object' === e(t)) {
                n = t.filePath;
            }
            -1 !== n.indexOf('//usr/')
                ? uni.getFileSystemManager().unlink({
                    filePath: n,
                    fail: function (e) {
                        console.error('removeSavedFile '.concat(t, ' failed, ').concat(JSON.stringify(e)));
                    }
                })
                : uni.removeSavedFile({
                    filePath: n,
                    fail: function (e) {
                        console.error('removeSavedFile '.concat(t, ' failed, ').concat(JSON.stringify(e)));
                    }
                });
        };
        for (a.s(); !(i = a.n()).done;) {
            o();
        }
    } catch (e) {
        console.log('CatchClause', e);
        console.log('CatchClause', e);
        a.e(e);
    } finally {
        a.f();
    }
}

exports.default = l;
